package com.xnx3.kefu.site.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xnx3.j2ee.util.SystemUtil;
import com.xnx3.BaseVO;
import com.xnx3.FileUtil;
import com.xnx3.j2ee.controller.BaseController;
import com.xnx3.j2ee.service.SqlCacheService;
import com.xnx3.j2ee.service.impl.SqlCacheServiceImpl;
import com.xnx3.kefu.core.entity.Kefu;
import com.xnx3.kefu.core.entity.KefuJS;
import com.xnx3.kefu.core.entity.Zuoxi;
import com.xnx3.kefu.core.util.KefuPropertiesUtil;

/**
 * 生成可以放到第三方网站的js
 * @author 管雷鸣
 */
@Controller(value="KefuSiteJSController")
@RequestMapping("/")
public class SiteKefuController extends BaseController {
	@Resource
	private SqlCacheService sqlCacheService;

	/**
	 * 获取当前客服的 kefuJS 信息
	 * @author 管雷鸣
	 * @param id 坐席的id
	 * @param template 模板名，不穿默认是2，位于 resources/static/template/ 下的文件夹
	 */
	@ResponseBody
	@RequestMapping("siteKefu.js")
	public String getKefuJS(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "id", required = true) String id,
			@RequestParam(value = "template", required = false, defaultValue = "2") String template){
		response.setContentType("text/javascript;charset=UTF-8");
		
		if(id.length() < 1){
			return "alert('kefu is null');";
		}
		//读取坐席id对应的kefu
//		Kefu kefu = sqlCacheService.findAloneByProperty(Kefu.class, "userid", id);
		Zuoxi zuoxi = sqlCacheService.findById(Zuoxi.class, id);
		if(zuoxi == null){
			return "alert('zuoxi not find');";
		}
//		Kefu kefu = sqlCacheService.findById(Kefu.class, zuoxi.getKefuid());
//		if(kefu == null){
//			return "kefu bucunzai";
//		}
		//读取自定义js
		KefuJS kefuJS = sqlCacheService.findById(KefuJS.class, zuoxi.getKefuid());
		if(kefuJS == null){
			kefuJS = new KefuJS();
		}
		String path = SystemUtil.getClassesPath()+"static/template/"+template+"/template.js";
//		String path = "/Users/apple/git/yunkefu/src/main/resources/static/js/yunkefu/siteKefu.js";
		String str = FileUtil.read(path);
		
		//获取一些参数
		String api = KefuPropertiesUtil.getProperty("kefu.api");
		if(api == null) {
			return "alert('please set kefu.properties - kefu.api');";
		}
		//容错，判断api是否末尾多加了/
		if(api.lastIndexOf("/") + 1 == api.length()) {
			//域名最后是以/结尾，那去掉最后的 /
			api = api.substring(0, api.length() -1);
		}
		
		str = str.replaceAll("\\{host\\}", api)
			.replaceAll("\\{socketUrl\\}", KefuPropertiesUtil.getProperty("kefu.socket"))
			.replaceAll("\\{zuoxiid\\}", zuoxi.getId())
			.replaceAll("\\{color\\}", kefuJS.getColor())
			.replaceAll("\\{backgroundColor\\}", kefuJS.getBackgroundColor());
		
		response.setContentType("text/javascript;charset=UTF-8");
		return str;
	}
	
}
